from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth.models import User
from userprofile.models import userprofile
from userprofile.views import renderProfile
from django.template import RequestContext
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from userattributes.models import Attribute, UserAttribute
from django.template import RequestContext

class userAttrForm(forms.Form):
	attr_id = forms.ChoiceField(label='Attribute', choices=[], required=False)

	def save(self, member_id, staff_id):
		data = self.cleaned_data
		if not int(data['attr_id']) == -1:
			member = User.objects.get(pk = member_id)
			attribute = Attribute.objects.get(pk = data['attr_id'])
			attr_exists = UserAttribute.objects.filter(user = member, attribute = attribute)
			if not len(attr_exists) == 1:
				staff = User.objects.get(pk = staff_id)
				usr_attr = UserAttribute(user = member, staff=staff, attribute = attribute)
				usr_attr.save()

class attrForm(forms.Form):
	attr = forms.CharField(label=(u'Attribute'), required=True)
	priority = forms.IntegerField(label=(u'Priority'), required=True)

	def checkForErrors(self):
		try:
			data = self.cleaned_data
			duplicate = Attribute.objects.get(name=data["attr"])
		except:
			pass
		else:
			return 'Error: a certification with this name already exists'
		return ''

	def save(self):
		data = self.cleaned_data
		new_attr = Attribute(name = data["attr"], priority=int(data["priority"]))
		new_attr.save()

def getChoiceAttrs():
	attrs = []
	attrs.append(('-1','---------'))
	all_attrs = Attribute.objects.all()
	for attr in all_attrs:
		attrs.append((attr.id, attr.name))
	return attrs

#Edit the global list of user attributes
@login_required(login_url='/accounts/login/')
def editAttrs(request):
	message = ''
	if request.user.is_staff:
		if request.method == 'POST':
			if 'add_attr' in request.POST:
				form = attrForm(request.POST)
				if form.is_valid():
					message = form.checkForErrors()
					if len(message) == 0:
						form.save()
			elif 'del_attr' in request.POST:
				selected = Attribute.objects.filter(id__in=request.POST.getlist('attr'))
				UserAttribute.objects.filter(attribute__in=selected).delete()
				selected.delete()
		form = attrForm()
		attrs = Attribute.objects.all()
		return render_to_response("userattributes/edit_attrs.html", {'form':form,
			'message':message,'attrs':attrs, 'csrf_token':csrf(request)['csrf_token']},
	context_instance=RequestContext(request))
	else:
		return render_to_response("unauth.html", {}, context_instance=RequestContext(request))

#Modify a user's attributes
@login_required(login_url='/accounts/login/')
def modifyAttrs(request, user_id):
	edited_user = User.objects.get(pk=user_id)
	if request.user.profile.gym_staff or request.user.is_staff:
		if request.method == 'POST':
			if 'add_attr' in request.POST:
				form = userAttrForm(request.POST)
				form.fields['attr_id'].choices = getChoiceAttrs()
				if form.is_valid():
					form.save(user_id, request.user.id)
			elif 'del_attr' in request.POST:
				UserAttribute.objects.filter(id__in=request.POST.getlist('attr')).delete()
		form = userAttrForm()
		form.fields['attr_id'].choices = getChoiceAttrs()
		user_attrs = UserAttribute.objects.filter(user=edited_user)
		return render_to_response("userattributes/modify_user.html", {'form':form,
	'edited_user':edited_user, 'attrs':user_attrs, 'csrf_token':csrf(request)['csrf_token']},
	context_instance=RequestContext(request))
	else:
		return render_to_response("unauth.html", {}, context_instance=RequestContext(request))

def getAttrs(user):
	attrs = []
	query = UserAttribute.objects.filter(user=user)
	for usr_attr in query:
		attribute = usr_attr.attribute
		name = attribute.name
		priority = attribute.priority
		attrs.append({"name": name, "priority":priority})
	sorted_attrs = sorted(attrs, key=lambda k: k['priority'], reverse=True)
	return sorted_attrs


@login_required(login_url='accounts/login/')
def listAttrs(request, user_id):
	if request.user.profile.gym_staff or request.user.is_staff or request.user.id == user_id:
		user = User.objects.get(pk=user_id)
		attrs = getAttrs(user)
		return render_to_response("userattributes/view.html", {"user":User.objects.get(pk=user_id),
			"attributes":attrs}, context_instance=RequestContext(request))
	else:
		return render_to_response("unauth.html", {}, context_instance=RequestContext(request))